let loadPromotions=require("./promotions");
let loadAllItems=require("./items");
function countFood(food){
  let result=[];
  for(let item of food){
    let num=parseInt(item.replace(/^[A-Z]{4}[0-9]{4}\sx\s/,""));
    let code=item.replace(/\sx\s[0-9]{1}/,"");
    result.push({id:code,count:num});
  }
  return result;
}
function addInformation(food){
  let allFood=loadAllItems();
  for(let item1 of allFood){
    for(let item2 of food){
      if(item1.id==item2.id){
        item2.name=item1.name;
        item2.price=item1.price;
      }
    }
  }
  return food;
}

function promotionsfood(food){
  let halfFood=loadPromotions()[1].items;
  let sum=0;
  for(let item of food){
    sum+=item.count*item.price;
  }
  console.log(sum);
  let sum_1=sum;
  let sum_2=sum;
  let promotion_name=[];
  //判断有无第一种优惠
  if(sum>=30){
    sum_1=sum-6;
  }

  //判断有无第二种优惠
  for(let item1 of food){
    for(let item2 of halfFood){
      if(item1.id==item2){
         sum_2-=item1.price/2*item1.count;
         promotion_name.push(item1.name);
      }
    }
  }
  let result;

  if(sum_1==sum&&sum_2==sum){
     result={way:0,saveMoney:0,total:sum};
  }
  else if(sum_1!=sum&&sum_2==sum){
     result={way:1,saveMoney:sum-sum_1,total:sum_1};
  }
  else if(sum_1==sum&&sum_2!=sum){
     result={way:2,saveMoney:sum-sum_2,total:sum_2,name:promotion_name};
  }
  else{
    if(sum_1<=sum_2){
       result={way:1,saveMoney:sum-sum_1,total:sum_1};
    }
    else{
       result={way:2,saveMoney:sum-sum_2,total:sum_2,name:promotion_name};
    }
  }
  return result;
}

function printList(discountWay,food){
  let result="============= 订餐明细 =============\n";
  for(let item of food){
    result+=item.name+" x "+item.count+" = "+item.price*item.count+"元\n";
  }
  result+='-----------------------------------\n'
  if(discountWay.way==1){
    result+='使用优惠:\n'+
    '满30减6元，省'+discountWay.saveMoney+'元\n'+'-----------------------------------\n';
  }
  else if(discountWay.way==2){
    let name=discountWay.name.join('，');
    //name=name.join('，');
    result+='使用优惠:\n'+
    '指定菜品半价('+name+')，省'+discountWay.saveMoney+'元\n'+
    '-----------------------------------\n'
  }
  result+='总计：'+discountWay.total+'元\n'+'===================================';
  return result;
}


function bestCharge(selectedItems) {
  let AfterCount=countFood(selectedItems);
  let AfterAddInformation=addInformation(AfterCount);
  let AfterDiscount=promotionsfood(AfterAddInformation);
  let list=printList(AfterDiscount,AfterAddInformation);
  return list;
}
module.exports=bestCharge;
bestCharge(["ITEM0013 x 4"]);